package com.though.weixin.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PublicConfig {

	private static final Logger logger = LoggerFactory.getLogger(PublicConfig.class);
	
	private static final String CONFIG = "/public-config.properties";

	private static final String CONFIG_TEMPLATE = "/public-config-template.properties";
	
	private volatile PublicConfigParams publicConfigParams;
	
	public PublicConfig() {
		init();
	}
	
	public void init() {
		InputStream in = PublicConfig.class.getResourceAsStream(CONFIG);
        if (in == null) {
            in = PayConfg.class.getResourceAsStream(CONFIG_TEMPLATE);
            if (in == null)
                throw new RuntimeException("public-config.properties is not config");
        }
		this.publicConfigParams = loadConfgParams(in);
	}

	private PublicConfigParams loadConfgParams(InputStream in) {
		Properties properties = new Properties();
		try {
			properties.load(in);
			
			String appid = properties.getProperty("weixin.appid");
			String token = properties.getProperty("weixin.token");
			String encodingAesKey = properties.getProperty("weixin.encodingAesKey");
			String secret = properties.getProperty("weixin.secret");
			String url = properties.getProperty("weixin.url");
            String callbackUrl = properties.getProperty("weixin.callbackUrl");
			
			PublicConfigParams params = new PublicConfigParams(appid, token, encodingAesKey, secret, url, callbackUrl);
			return params;
			
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					logger.error("Error:close oss propertis file", e);
				}
			}
		}
	}

	public PublicConfigParams getConfigParams() {
		return publicConfigParams;
	}
}
